package com.groupscore.score.controller;

import com.groupscore.score.config.AliyunOssConfig;
import com.groupscore.score.pojo.*;
import com.groupscore.score.pojogroup.GroupScore;
import com.groupscore.score.pojogroup.PersonalOptionScore;
import com.groupscore.score.service.*;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import util.JwtUtil;
import util.OssTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/userException")
public class UserExceptionController {

    @Autowired
    private UserExcepitionService userExcepitionService;


    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TeamService teamService;


    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private ExcepitionCatService excepitionCatService;
    @Autowired
    private ChapterService chapterService;


    //文件最大上传大小
    public static long FILE_MAX_SIZE = 1024 * 1024 * 10;

    //图片过期时间 1年
    public static long FILE_EXPIRATION_TIME = 1000 * 3600 * 24 * 365 * 1;

    /**
     * 添加异常
     */
    @PostMapping
    @RequestMapping("/add")
    @CrossOrigin
    public Result add(@RequestBody UserException userException){

        Map map = new HashMap(  );

        //设置分类名称
        userException.setCatName( excepitionCatService.findOne( userException.getCatId() ).getName() );
        //设置章节名称
        userException.setChapterName( chapterService.findOne( userException.getChapterId() ).getName() );

        userException.setCreateTime( new Date() );

        //jwt解析token,从中获取出用户id
        Claims claims = jwtUtil.parseJWT(userException.getToken());
        if (claims == null) {
            return new Result(false, StatusCode.ACCESSERROR,"无权访问");
        }

        String userId = claims.getId();
        userException.setUserId( userId );
        userExcepitionService.save( userException );
        return new Result(true, StatusCode.OK, "提交成功");
    }

    @ApiOperation("文件上传功能")
    @PostMapping("/upload")
    @CrossOrigin
    public Result upload(@RequestParam("file") MultipartFile[] fileList)throws IOException {

        Map<String,Object> map = new HashMap<>();
        List<String> list= new ArrayList<>();
        if(fileList!=null&&fileList.length>0){
            for(MultipartFile item:fileList){
                if(!item.isEmpty()){

                    if (item.getSize() <= 0 || item.getSize() > AliyunOssConfig.FILE_MAX_SIZE) {
                        return new Result(false, StatusCode.ERROR, "文件不能大于1M");
                    }

                    String upload = ossTemplate.upload(item.getInputStream(),item.getOriginalFilename());
                    list.add(upload);
                }
            }
        }
        map.put("urls",list);
        return new Result(true, StatusCode.OK, "上传成功",list );
    }



    /**
     * 删除
     */
    @GetMapping
    @RequestMapping("/delete")
    @CrossOrigin
    public Result delete(Integer id){

        Map map = new HashMap(  );
        userExcepitionService.deleteById( id );
        return  new Result(true, StatusCode.OK, "查询成功",null);
    }



  /**
   * 修改
   * @param userException
   */
  @CrossOrigin
  @RequestMapping(value = "/update/{id}",method = RequestMethod.PUT)
  public Result update(@RequestBody UserException userException, @PathVariable Integer id ){

      userExcepitionService.update(userException);
     return new Result(true, StatusCode.OK,"修改成功");
  }

  @CrossOrigin
  @GetMapping(value = "findByUserId")
  public Result findByUserId( String token){
      //jwt解析token,从中获取出用户id
      Claims claims = jwtUtil.parseJWT(token);
      if (claims == null) {
          return new Result(false, StatusCode.ACCESSERROR,"无权访问");
      }
      
      //取出用户id
      String userId = claims.getId();
      return new Result(true, StatusCode.OK,"查询成功", userExcepitionService.findByUserId( userId ));
  }

    @CrossOrigin
    @GetMapping(value = "findById")
    public Result findById( String id){

        return new Result(true, StatusCode.OK,"查询成功", userExcepitionService.findById( id ));
    }

    @CrossOrigin
    @GetMapping(value = "findAll")
    public Result findAll( String token){
        //jwt解析token,从中获取出用户id
        Claims claims = jwtUtil.parseJWT(token);
        if (claims == null) {
            return new Result(false, StatusCode.ACCESSERROR,"无权访问");
        }
        return new Result(true, StatusCode.OK,"查询成功", userExcepitionService.findAll( ));
    }

    /**
     * 分页条件查询
     */
    @CrossOrigin
    @PostMapping(value = "/search")
    public Result search( String token,@RequestBody Map whereMap,int page, int size){
        //jwt解析token,从中获取出用户id
        Claims claims = jwtUtil.parseJWT(token);
        if (claims == null) {
            return new Result(false, StatusCode.ACCESSERROR,"无权访问");
        }
        return new Result(true, StatusCode.OK,"查询成功", userExcepitionService.findSearch(whereMap, page, size ));
    }
}
